import {
  ForumsItem,
  PostsItem,
  TagsItem,
  getCategories,
  getForums,
  getPosts,
  getTags,
} from "@/api/question";
import { List, Tabs, Typography } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";

const ListBox = ({ title }: { title: string }) => {
  const navigate = useNavigate();
  const [dataSource, setDataSource] = useState<PostsItem[] | ForumsItem[]>([]);
  const [page, setPage] = useState(1);
  const pageSize = 10;
  const [tags, setTags] = useState<string[]>([]);
  const [categories, setCategories] = useState<string[]>([]);
  const titleIndex = useCallback(
    (idx: number) => {
      return (page - 1) * pageSize + idx + 1;
    },
    [page]
  );
  useEffect(() => {
    if (title === "blog") {
      getTags().then((data) => {
        setTags(data.map((tag) => tag.tagName));
      });
    } else if (title === "forums") {
      getCategories().then((data) => {
        setCategories(data.map((categories) => categories.categoryName));
      });
    }
  }, [title]);

  const tabItems = useMemo(() => {
    let items = [{ label: "全部", key: "" }];
    if (title === "blog") {
      items = items.concat(
        tags.map((it) => ({
          label: it,
          key: it,
        }))
      );
    } else if (title === "forums") {
      items = items.concat(
        categories.map((it) => ({
          label: it,
          key: it,
        }))
      );
    }
    console.log(items, categories, tags);
    return items;
  }, [title, categories, tags]);
  const handleTabsChange = (key: string) => {
    if (title === "blog") {
      getPosts({
        tag: key,
      }).then((data) => {
        setDataSource(data);
      });
    } else if (title === "forums") {
      getForums({
        categories: key,
      }).then((data) => {
        setDataSource(data);
      });
    }
  };
  return (
    <List
      header={<Tabs centered onChange={handleTabsChange} items={tabItems} />}
      bordered
      style={{
        width: "70%",
        margin: "auto",
        marginTop: "50px",
        backgroundColor: "#fff",
      }}
      pagination={{
        onChange: (page) => {
          setPage(page);
        },
        pageSize,
      }}
      dataSource={dataSource}
      renderItem={(it, index) => (
        <List.Item
          style={{ cursor: "pointer" }}
          onClick={() =>
            navigate("/detail", {
              state: {
                ...dataSource[index],
                isForums: title === "forums",
              },
            })
          }
        >
          {titleIndex(index)}. {it.title}
        </List.Item>
      )}
    />
  );
};

export default ListBox;
